package com.huiyin.ui.user.order;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.R.integer;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.reflect.TypeToken;
import com.grong.hyin.sdk.entity.ToastUtils;
import com.huiyin.AppContext;
import com.huiyin.R;
import com.huiyin.adapter.BackGoodsAdapter;
import com.huiyin.adapter.ReplaceGoodsAddAdapter;
import com.huiyin.adapter.ReplaceTypeAdapter;
import com.huiyin.adapter.UploadImageAdapter;
import com.huiyin.api.CustomResponseHandler;
import com.huiyin.api.RequstClient;
import com.huiyin.base.BaseCameraActivity;
import com.huiyin.bean.GoodList;
import com.huiyin.bean.GoodsListEntity;
import com.huiyin.bean.ImageData;
import com.huiyin.bean.OrderRecordBean;
import com.huiyin.bean.ReplaceListEntity;
import com.huiyin.bean.ReservationType;
import com.huiyin.bean.ReturnListEntity;
import com.huiyin.http.RequestParams;
import com.huiyin.newpackage.entity.GoodsDetail;
import com.huiyin.newpackage.entity.OrderInfo;
import com.huiyin.newpackage.ui.activity.AgreementWebViewActivity;
import com.huiyin.ui.housekeeper.SelectApplyReasonWindow.IOnItemClick;
import com.huiyin.utils.DeviceUtils;
import com.huiyin.utils.JSONParseUtils;
import com.huiyin.utils.imageupload.ImageUpload.UpLoadImageListener;
import com.huiyin.wight.MyListView;

/**
 * 修改退货
 * 刘晨旭
 */
public class BackGoodsForUpdateaInfoActivity extends BaseCameraActivity implements OnItemClickListener, OnClickListener {

	/** 数据模型 **/
	public static final String EXTRA_MODEL = "model";

	/** 订单ID **/
	public static final String EXTRA_ORDERID = "orderId";

	/** 售后类型 **/
	public static final String EXTRA_SEARCH_TYPE = "searchType";

	/** 换货Id / 退货Id **/
	public static final String EXTRA_SEARCHID = "searchId";

	/** 售后类型-换货 **/
	public static final int SEARCH_REPLACE = 0;

	/** 售后类型-退货 **/
	public static final int SEARCH_RETURN = 1;

	/** 商品列表 **/
	private MyListView lvproduct;

	/** 售后类型 **/
	private MyListView lvsaleaftertype;

	/** 申请理由 **/
	private TextView applyResonTv;

	/** 描述问题 **/
	private EditText remarkinfo;

	/** 描述问题-提示(0-200) **/
	private TextView remarkinfotip;

	/** 我已阅读 **/
	private CheckBox readCheckbox;

	/** 提交申请 **/
	private Button submitBtn;

	/** 上传图片 **/
	private GridView uploadGridView;

	/** 商品适配器 **/
	private BackGoodsAdapter adapter;

	/** 售后类型适配器 **/
	private ReplaceTypeAdapter typeAdapter;

	/** 图片上传适配器 **/
	private UploadImageAdapter uploadImageAdapter;

	/** 订单ID **/
	private String orderId;
	
	
	private List<ImageData> imageDatas=new ArrayList<ImageData>();
	
	//初始化的时候的保存传过来的上传的图片的的urls
	List<String> picsList=new ArrayList<String>();

	// /** 申请售后model数据 **/
	// private OrderRecordBean returnBean;

	// 单个退货的时候，通过这个值来确定哪个货物是需要退的
	// 这个值为空或者null
	// 表示是整单退款
	private String needReturnGoodsIdString = "";

	private OrderInfo order;

	private List<ReturnListEntity> reasons = new ArrayList<ReturnListEntity>();
	
	private TextView tv_title;
	
	private String order_service_detail_id="";
	
	private String order_service_id="";
	
	private boolean isComplete=true;//标识是整单退款还是申请售后
	private RelativeLayout apply_count_layout;
	private ImageView adapter_minus;
	private ImageView adapter_plus;
	private EditText adapter_goods_num;
	private TextView aggrement;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_backgoods);

		// 初始化控件
		initView();

		// 初始化数据
		initData();

		initReasons();
	}

	/**
	 * 初始化退货原因
	 */
	private void initReasons() {
		RequstClient.getReasonList(new CustomResponseHandler(mContext, false) {
			@Override
			public void onRefreshData(String content) {
				int type = JSONParseUtils.getInt(content, "type");
				if (type == 1) {
					try {
						JSONObject object = new JSONObject(content);
						JSONArray array = object.getJSONArray("reasonList");
						Gson gson = new Gson();
						List<ReturnReason> retList = gson.fromJson(array.toString(),
								new TypeToken<List<ReturnReason>>() {
								}.getType());
						reasons.clear();
						for (ReturnReason returnReason : retList) {
							ReturnListEntity entity = new ReturnListEntity();
							entity.setID(returnReason.STATE_VALUE);
							entity.setNAME(returnReason.STATE_NAME);
							reasons.add(entity);
						}
					} catch (JSONException e) {
						showMyToast("数据异常");
						e.printStackTrace();
					}
				} else {
					String msg = JSONParseUtils.getString(content, "msg");
					// 显示服务器返回的异常信息
					showMyToast(msg);
				}
			}

		});
	}

	/**
	 * 初始化控件
	 */
	private void initView() {

		//申请数量布局
		apply_count_layout=(RelativeLayout)findViewById(R.id.apply_count_layout);
		adapter_minus=(ImageView)findViewById(R.id.adapter_minus);
		adapter_plus=(ImageView)findViewById(R.id.adapter_plus);
		adapter_goods_num=(EditText)findViewById(R.id.adapter_goods_num);
		aggrement=(TextView) findViewById(R.id.aggrement);
		
		this.uploadGridView = (GridView) findViewById(R.id.upload_gridview);
		this.applyResonTv = (TextView) findViewById(R.id.apply_reson_textview);

		this.remarkinfo = (EditText) findViewById(R.id.remark_info);
		this.remarkinfotip = (TextView) findViewById(R.id.remark_info_tip);
		this.lvsaleaftertype = (MyListView) findViewById(R.id.lv_saleafter_type);
		this.lvproduct = (MyListView) findViewById(R.id.lv_product);
		this.submitBtn = (Button) findViewById(R.id.submit_apply_btn);
		this.readCheckbox = (CheckBox) findViewById(R.id.read_checkbox);

		// 设置适配器
		adapter = new BackGoodsAdapter(mContext, null);
		lvproduct.setAdapter(adapter);
		typeAdapter = new ReplaceTypeAdapter(mContext, null);
		lvsaleaftertype.setAdapter(typeAdapter);

		int screenWidth = DeviceUtils.getWidthMaxPx(mContext);
		uploadImageAdapter = new UploadImageAdapter(mContext, screenWidth, 5);
		uploadGridView.setAdapter(uploadImageAdapter);

		// 监听描述问题文本变换
		setTextChangeListener(remarkinfo, remarkinfotip, 200);
		uploadGridView.setOnItemClickListener(this);
		lvsaleaftertype.setOnItemClickListener(this);
		lvproduct.setOnItemClickListener(this);

		submitBtn.setOnClickListener(this);
		findViewById(R.id.apply_reason_layout).setOnClickListener(this);
		
		tv_title=(TextView)findViewById(R.id.tv_title);
		tv_title.setText("修改申请");
		aggrement.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent=new Intent(BackGoodsForUpdateaInfoActivity.this,AgreementWebViewActivity.class);
				intent.putExtra("KEY_TITLE", "退换货条款");
				intent.putExtra("KEY_FLAG", "362");
				BackGoodsForUpdateaInfoActivity.this.startActivity(intent);
			}
		});
		initServiceNum();
	}
	
	
	/**
	 * 初始化申请数量的事件方法
	 */
	private void initServiceNum(){
		// 数量减
		adapter_minus.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (Integer.parseInt(adapter_goods_num.getText().toString()) == 1) {
					ToastUtils.show(BackGoodsForUpdateaInfoActivity.this, "退货商品数量不能少于1", Toast.LENGTH_SHORT);
				} else {
					adapter_goods_num.setText((Integer.parseInt(adapter_goods_num.getText().toString()) - 1) + "");
					adapter.getReturnGoodsList().get(0).NUM_GOODS_NEED_RETURN = ((Integer.parseInt(adapter_goods_num.getText()
							.toString())) + "");
				}
			}
		});
		
		// 数量加
		adapter_plus.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (Integer.parseInt(adapter_goods_num.getText().toString()) == Integer.parseInt(
						adapter.getReturnGoodsList().get(0).getQUANTITY()+ "")) {
					ToastUtils.show(BackGoodsForUpdateaInfoActivity.this, "退货商品数量不能大于购买商品的数量", Toast.LENGTH_SHORT);
				} else {
					adapter_goods_num.setText((Integer.parseInt(adapter_goods_num.getText().toString()) + 1) + "");
					adapter.getReturnGoodsList().get(0).NUM_GOODS_NEED_RETURN = ((Integer.parseInt(adapter_goods_num.getText()
							.toString())) + "");
				}
			}
		});
		
		/**
		 * 编辑框输入数字限制大小
		 */
		adapter_goods_num.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {

			}
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {

			}
			@Override
			public void afterTextChanged(Editable s) {
				String num = adapter_goods_num.getText().toString();
				if (!TextUtils.isEmpty(num)) {
					if (Integer.parseInt(num) > Integer.parseInt(adapter.getReturnGoodsList().get(0).getQUANTITY() + "")) {
						ToastUtils.show(BackGoodsForUpdateaInfoActivity.this, "退货商品数量不能大于购买商品的数量", Toast.LENGTH_SHORT);
						adapter_goods_num.setText(adapter.getReturnGoodsList().get(0).getQUANTITY() + "");
					}
					adapter.getReturnGoodsList().get(0).NUM_GOODS_NEED_RETURN = ((Integer.parseInt(adapter_goods_num.getText()
							.toString())) + "");
				}
			}
		});
		
		/**
		 * 失去焦点的时候 如果输入框中为空 那么设置为初始值
		 */
		adapter_goods_num.setOnFocusChangeListener(new OnFocusChangeListener() {
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				if (!hasFocus) {
					String num = adapter_goods_num.getText().toString();
					if (TextUtils.isEmpty(num)) {
						adapter_goods_num.setText(adapter.getReturnGoodsList().get(0).getQUANTITY() + "");
						adapter.getReturnGoodsList().get(0).NUM_GOODS_NEED_RETURN = ((Integer.parseInt(adapter_goods_num
								.getText().toString())) + "");
					}
				}
			}
		});
	}

	/**
	 * 初始化数据
	 */
	private void initData() {
		// 售后类型
		Intent intent = getIntent();
		if (null != intent) {
			// 订单ID
			this.orderId = intent.getStringExtra(EXTRA_ORDERID);

			this.needReturnGoodsIdString = intent.getStringExtra("ID");
			
			this.order_service_detail_id=intent.getStringExtra("order_service_detail_id");

			this.order = (OrderInfo) intent.getSerializableExtra("Order");
			
			this.order_service_id=(String)intent.getSerializableExtra("order_service_id");

			if (this.order == null) {
				this.finish();
			}
			for (int i = 0; i < order.getOrderDetalList().size(); i++) {
				order.getOrderDetalList().get(i).setInitNumGoodsNeedReturn();
			}
			showData();
		}
	}

	private void showData() {
		if (order == null || order.getOrderDetalList() == null || order.getOrderDetalList().size() == 0) {
			return;
		}
		// 显示商品信息
		if (!TextUtils.isEmpty(this.needReturnGoodsIdString)) {
			List<GoodsDetail> entitysEntities = new ArrayList<GoodsDetail>();
			for (int i = 0; i < order.getOrderDetalList().size(); i++) {
				if ((order.getOrderDetalList().get(i).getGOODS_ID() + "").equals(this.needReturnGoodsIdString)) {
					entitysEntities.add(order.getOrderDetalList().get(i));
				}
			}
			order.getOrderDetalList().clear();
			order.getOrderDetalList().addAll(entitysEntities);
			adapter.refreshData(order.getOrderDetalList(),false);
			apply_count_layout.setVisibility(View.VISIBLE);
			adapter_goods_num.setText(adapter.getReturnGoodsList().get(0).NUM_GOODS_NEED_RETURN);
			//购买数量为1 这个时候不能增加也不能减少
			if(adapter_goods_num.getText().toString().equals("1")){
				adapter_minus.setEnabled(false);
				adapter_minus.setImageResource(R.drawable.mashangjiesuan_03_disable);
				adapter_plus.setEnabled(false);
				adapter_plus.setImageResource(R.drawable.mashangjiesuna_08_disable);
				adapter_goods_num.setEnabled(false);
				adapter_goods_num.setBackgroundResource(R.drawable.shopping_num_input_bg_disable);
			}
			else{
				adapter_minus.setEnabled(true);
				adapter_minus.setImageResource(R.drawable.mashangjiesuan_03);
				adapter_plus.setEnabled(true);
				adapter_plus.setImageResource(R.drawable.mashangjiesuna_08);
				adapter_goods_num.setEnabled(true);
				adapter_goods_num.setBackgroundResource(R.drawable.shopping_num_input_bg);
			}
		} else {
			apply_count_layout.setVisibility(View.GONE);
			apply_count_layout.setEnabled(false);
			adapter.refreshData(order.getOrderDetalList(),true);
		}
		// 设置售后类型数据
		ReservationType type = new ReservationType();
		type.RESERVATIONTYP_NAME = "退货";
		type.RESERVATIONTYP_ID = 1 + "";
		List<ReservationType> dataList = new ArrayList<ReservationType>();
		dataList.add(type);
		typeAdapter.refreshData(dataList);
		typeAdapter.checkPosition(0);
		applyResonTv.setText(order.getAPPLY_REASON());//申请理由
		remarkinfo.setText(order.getAPPLY_REMARK());//问题描述
		String picsUrls = order.getAPPLY_IMGS();//上传图片
		if(!TextUtils.isEmpty(picsUrls)){
			picsList = Arrays.asList(picsUrls.split(","));
			if (!(picsList == null || picsList.size() == 0)) {
				for (String string : picsList) {
					ImageData data = new ImageData(string, string);
					imageDatas.add(data);
				}
				uploadImageAdapter.refreshData(imageDatas);
			}
		}
	}

	/**
	 * 换货新增
	 */
	private void ReturnGoods(String img) {
		String orderId = this.orderId;
		String userId = AppContext.userId;
//		String reasonId = applyResonTv.getTag().toString().trim();
		String reasonName = applyResonTv.getText().toString().trim();
		List<GoodsDetail> goodsList = adapter.getCheckedGoods();
		String describe = getText(remarkinfo);
		String origin = "3";

		RequestParams params = new RequestParams();
		params.put("order_service_id", order_service_id+"");
		params.put("apply_pictures", img);
		params.put("apply_reason", reasonName);
		params.put("apply_remarks", describe);
		params.put("service_type", 1 + "");
		params.put("order_service_detail_id", order_service_detail_id);
		if (TextUtils.isEmpty(needReturnGoodsIdString)) {
			params.put("is_complete", 1 + "");// 整单
		} else {
			params.put("is_complete", 0 + "");// 单个 非整单
			params.put("goods_id", needReturnGoodsIdString);
			List<GoodsDetail> lists = adapter.getReturnGoodsList();
			for (GoodsDetail goodsListEntity : lists) {
				if ((goodsListEntity.getGOODS_ID() + "").equals(needReturnGoodsIdString)) {
					params.put("quantity", goodsListEntity.NUM_GOODS_NEED_RETURN);
				}
			}
		}
		RequstClient.submitUpdateBackGoodsApply(params, new CustomResponseHandler(mContext, true) {
			@Override
			public void onRefreshData(String content) {
				// 解析json
				int type = JSONParseUtils.getInt(content, "type");
				if (type == 1) {
					finish();
				} else {
					String msg = JSONParseUtils.getString(content, "msg");
					// 显示服务器返回的异常信息
					showMyToast(msg);
				}
			}

		});
	}

	/**
	 * 提交申请
	 */
	private void submitApply(String img) {
		// 我要退货
		ReturnGoods(img);
	}

	/**
	 * 设置默认的申请理由
	 * 
	 * @param applyType
	 */
	private void setDefaultApplyReason(String applyType) {

		try {
			// 代表退货ID
			if (applyType.equals("1")) {

				// 我要退货
				ReturnListEntity a = reasons.get(0);
				applyResonTv.setTag(a.getID());
				applyResonTv.setText(a.getNAME());

			}
		} catch (Exception e) {
			// 这里可能会报数组越界
			e.printStackTrace();
		}

	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {

		switch (arg0.getId()) {
		case R.id.lv_saleafter_type:

			// 售后类型
			boolean hasChangeType = typeAdapter.checkPosition(arg2);

			// 设置默认的申请理由
			if (hasChangeType) {
				ReservationType type = (ReservationType) typeAdapter.getItem(arg2);
				setDefaultApplyReason(type.RESERVATIONTYP_ID);
			}

			break;
		case R.id.lv_product:

			// delete by zhyao @2016/7/5 商品默认全选，并且不让删除
			// //商品列表
			// GoodsListEntity bean = (GoodsListEntity)adapter.getItem(arg2);
			// adapter.checkProduct(bean);

			break;
		case R.id.upload_gridview:

			// 上传图片
			if (uploadImageAdapter.isClickAddPic(arg2)) {

				// 打开相册，相机
				showCameraPopwindow(arg1, false, false);
			}

			break;
		}

	}

	@Override
	public void onUpLoadSuccess(String imageUrl, String imageFile) {

		// 非空判断
		if (TextUtils.isEmpty(imageUrl) && TextUtils.isEmpty(imageFile)) {
			return;
		}

		// 显示新增的数据
		uploadImageAdapter.appendData(new ImageData(imageFile, imageUrl));
	}

	@Override
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.submit_apply_btn:

			// 提交申请
			if (validateInput()) {
				ArrayList<ImageData> needUploadDatas=new ArrayList<ImageData>();
				final ArrayList<ImageData> alreadyUploadedDatas=new ArrayList<ImageData>();
				for (int i = 0; i < uploadImageAdapter.getDataList().size(); i++) {
					if(!(picsList.contains(uploadImageAdapter.getDataList().get(i).fileName))){
						needUploadDatas.add(uploadImageAdapter.getDataList().get(i));
					}
					else{
						alreadyUploadedDatas.add(uploadImageAdapter.getDataList().get(i));
					}
				}
				uploadImage(needUploadDatas, new UpLoadImageListener() {

					@Override
					public void UpLoadSuccess(ArrayList<String> netimageurls) {
						// 上传成功的图片
						String img = getImgs(netimageurls);
						if(!TextUtils.isEmpty(img)){
							for (int i = 0; i < alreadyUploadedDatas.size(); i++) {
								img=img+","+alreadyUploadedDatas.get(i).imgUrl;
							}	
						}
						else{
							for (int i = 0; i < alreadyUploadedDatas.size(); i++) {
								if(i==0){
									img=alreadyUploadedDatas.get(i).imgUrl;
								}
								else{
									img=img+","+alreadyUploadedDatas.get(i).imgUrl;
								}
							}
						}
						// 提交申请
						submitApply(img);
					}

					@Override
					public void UpLoadFail() {
						showMyToast("图片上传失败");
					}
				});
			}

			break;
		case R.id.apply_reason_layout:

			// 申请理由
			String typeId = typeAdapter.getCurTypeId();
			if (typeId.equals("1")) {

				// 我要退货
				showReasonPopwindow(view, getReturnDataMap(reasons), new IOnItemClick() {

					@Override
					public void onItemClick(String id, String value) {
						applyResonTv.setTag(id);
						applyResonTv.setText(value);
					}
				});

			}

			break;
		}
	}

	/**
	 * 根据List<String>获得 "str1,str2,str3..."
	 * 
	 * @param netimageurls
	 * @return
	 */
	public String getImgs(List<String> netimageurls) {
		if (null == netimageurls || netimageurls.size() == 0) {
			return "";
		}
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < netimageurls.size(); i++) {
			if (i == 0) {
				sb.append(netimageurls.get(i));
			} else {
				sb.append("," + netimageurls.get(i));
			}
		}

		return sb.toString();
	}

	/**
	 * 获取数据map
	 * 
	 * @param dataList
	 * @return
	 */
	private Map<String, String> getReturnDataMap(List<ReturnListEntity> dataList) {
		Map<String, String> dataMap = new HashMap<String, String>();
		for (int i = 0; i < dataList.size(); i++) {
			dataMap.put(dataList.get(i).getID() + "", dataList.get(i).getNAME());
		}
		return dataMap;
	}

	/**
	 * 获取数据map
	 * 
	 * @param dataList
	 * @return
	 */
	private Map<String, String> getReplaceDataMap(List<ReplaceListEntity> dataList) {
		Map<String, String> dataMap = new HashMap<String, String>();
		for (int i = 0; i < dataList.size(); i++) {
			dataMap.put(dataList.get(i).getID() + "", dataList.get(i).getNAME());
		}
		return dataMap;
	}

	/**
	 * 输入有效性验证
	 * 
	 * @return
	 */
	public boolean validateInput() {

		List<GoodsDetail> goods = adapter.getCheckedGoods();

		if (null == goods || goods.size() == 0) {
			showMyToast("请选择商品");
			return false;
		}

		if (!readCheckbox.isChecked()) {
			showMyToast("请阅读 退换货条款");
			return false;
		}

		if (TextUtils.isEmpty(applyResonTv.getText().toString())) {
			showMyToast("请选择申请理由");
			return false;
		}
		
		String des = remarkinfo.getText().toString().trim();
		if (TextUtils.isEmpty(des)) {
			showMyToast("请填写问题描述");
			return false;
		}
		return true;
	}

	class ReturnReason implements Serializable {
		private int STATE_VALUE;
		private String STATE_NAME;

		public int getSTATE_VALUE() {
			return STATE_VALUE;
		}

		public void setSTATE_VALUE(int sTATE_VALUE) {
			STATE_VALUE = sTATE_VALUE;
		}

		public String getSTATE_NAME() {
			return STATE_NAME;
		}

		public void setSTATE_NAME(String sTATE_NAME) {
			STATE_NAME = sTATE_NAME;
		}

	}
}
